/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2019 HUST Dian Group
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Original Author: Pengyu Liu    <eicliupengyu@gmail.com>
 */
#include "ns3/log.h"
#include "ns3/double.h"
#include "robo-common.h"
#include "variable-speed-mobility.h"

#include "robo-base.h"

namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (VariableSpeedMobility);
NS_LOG_COMPONENT_DEFINE ("VariableSpeedMobility");
VariableSpeedMobility::VariableSpeedMobility ()
{
  NS_LOG_FUNCTION (this);
  m_speed = FVector (0, 0);
  m_maxSpeed = 0.f;
}

VariableSpeedMobility::~VariableSpeedMobility ()
{
  NS_LOG_FUNCTION (this);
}

TypeId
VariableSpeedMobility::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::VariableSpeedMobility")
                          .SetParent<RoboMobility> ()
                          .SetGroupName ("Robo")
                          .AddAttribute ("MaxSpeed", "Max speed", DoubleValue (M_FLOAT_MAX),
                                         MakeDoubleAccessor (&VariableSpeedMobility::m_maxSpeed),
                                         MakeDoubleChecker<float> ());
  return tid;
}

TypeId
VariableSpeedMobility::GetInstanceTypeId (void) const
{
  return GetTypeId ();
}

void
VariableSpeedMobility::SetActor (Ptr<RoboActor> actor)
{
  NS_LOG_FUNCTION (this);
  RoboMobility::SetActor (actor);
  m_lastLocation = m_actor->m_globalLocation;
}

void
VariableSpeedMobility::SetSpeed (FVector speed)
{
  float fspeed = speed.GetLength ();
  m_speed = fspeed < m_maxSpeed ? speed : speed * m_maxSpeed / std::max (fspeed, 1e-6f);
}

FVector
VariableSpeedMobility::GetSpeed (void) const
{
  return m_speed;
}

float
VariableSpeedMobility::GetMaxSpeed (void) const
{
  return m_maxSpeed;
}

void
VariableSpeedMobility::SetMaxSpeed (float speed)
{
  m_maxSpeed = speed;
}

void
VariableSpeedMobility::UpdateLocation (float delta)
{
  NS_LOG_FUNCTION (this);
  if (m_actor->m_isDestroy || m_actor->m_isDeleted)
    return;
  m_lastLocation = m_actor->m_globalLocation;
  m_actor->m_globalLocation += m_speed * delta;
}

void
VariableSpeedMobility::RollBackLocation (void)
{
  m_actor->m_globalLocation = m_lastLocation;
}

Vector
VariableSpeedMobility::DoGetVelocity (void) const
{
  return Vector (m_speed.m_x, m_speed.m_y, 0.0);
}
} // namespace ns3
